package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        ex.printStackTrace();
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler
    public Result exceptionHandler(DuplicateKeyException ex){
        ex.printStackTrace();
        System.out.println("4、全局异常处理器获取当前线程ID："+Thread.currentThread().getId());
        log.error("异常信息：{}", ex.getMessage());
        String exMessage = ex.getMessage();
        if (exMessage.contains("Duplicate entry")){
            String username = exMessage.split(" ")[9].replace("'", "");
            String message = "用户已存在：【"+username+"】";
            return Result.error(message);
        }
        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }

    @ExceptionHandler
    public Result exceptionHandler(Exception ex){
        ex.printStackTrace();
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(MessageConstant.UNKNOWN_ERROR);

    }


}
